<?php
/**
 * Created by PhpStorm.
 * User: aDaddy
 * Date: 2016/7/25
 * Time: 9:55
 */

namespace Model\CourseBundle\Model;
use Base\BaseModel;
use Model\CourseBundle\Setting\CourseSetting;
use Model\CourseCollectBundle\Model\CourseCollectModel;
use Model\CourseLikesBundle\Model\CourseLikesModel;

class CourseModel extends BaseModel{

    /*
     * 列表基本设置【通用模块必须开发】
     */
    public function listSettingDefault()
    {
        $settings = new CourseSetting($this->getDoctrine());
        return $settings->listConfig();
    }

    /**
     * @param array $params $param[textKey]=textKey , $param[conditions][table][field][eq|gt|lt...]=value , $param[orderBy][table][field]=DESC|ASC
     * @param int $offset
     * @param int $perPage
     * @return array
     */
    public function getAdminLists($params ,$offset = 0 , $perPage = 10)
    {
        $qb = $this->getQueryFromParam($params);
        $lists = $this->getAllResult($qb,$offset,$perPage);
        $total = $this->countAllResult($qb);

        return array(
            "total" => $total ? $total : 0,
            "data"  => $lists
        );
    }

    public function getOneArray($id,$userId)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("*")
            ->where("id = ?")
            ->setParameter(0,$id)
            ->andWhere("userId = ?")
            ->setParameter(1,$userId)
            ->from("Course");
        return $qb->execute()->fetch();
    }

    public function getOneById($id)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("*")
            ->where("id = ?")
            ->setParameter(0,$id)
            ->from("Course");
        return $qb->execute()->fetch();
    }
    public function getOneByUniqueId($uniqueId)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("*")
            ->where("uniqueId = ?")
            ->setParameter(0,$uniqueId)
            ->from("Course");
        return $qb->execute()->fetch();
    }

    public function commAdd($params)
    {

        //设置默认值
        $defaults = array(
            "title"     => "课程标题被外星人抹去了！",
            "userId"    => 0,
            "category"  => 1,
            "picCover"  => "课程封面默认图",//todo 设计一下
            "picMain"   => "课程主图默认图",//todo 设计一下
            "info"      => "希望我们为您精心准备的课程能对您有些许帮助",
            "status"    => 0,
            "addTime"   => time(),
            "updateTime"=> time(),
            "isHot"     => 0,
            "isTop"     => 0,
            "isRecommend"=> 0,
            "studentNow"=> 0,
            "studentHistory"=> 0,
            "hit"       => 0,
            "likes"     => 0,
            "uniqueId"  => md5(time().uniqid())
        );
        foreach ($defaults as $k => &$v) {
            if (isset($params[$k]) && $params[$k] !== "") {
                $v = $params[$k];
            }
        }
        $qb = $this->getQueryBuilder();
        if (isset($params["id"])) {

//            var_dump($params);die;
            //编辑
            $qb->update("Course");
            $qb->where("id = :id")->setParameter("id",$params["id"]);
            foreach ($defaults as $key => $val) {
                $qb->set("$key",":$key")->setParameter(":$key",$val);
            }
        } else {
            //新增
            $qb->insert("Course");
            $keys = array_keys($defaults);
            $values = array_values($defaults);
            $insertKeys = array();
            foreach ($keys as $k => $val) {
                $insertKeys[$val] = "?";
            }
            $qb->values($insertKeys)->setParameters($values);
        }
        $qb->execute();
        if ( $qb->getState() === 1) {
            return $defaults["uniqueId"];
        } else {
            return $qb->getState();
        }
    }
    public function commUpdate($params)
    {

        //设置默认值
        $defaults = array(
            "title"     => "课程标题被外星人抹去了！",
            "userId"    => 0,
            "category"  => 1,
            "picCover"  => "/public/default_course.png",
            "picMain"   => "课程主图默认图",//todo 设计一下
            "info"      => "希望我们为您精心准备的课程能对您有些许帮助",
            "status"    => 0,
            "addTime"   => time(),
            "updateTime"=> time(),
            "isHot"     => 0,
            "isTop"     => 0,
            "isRecommend"=> 0,
            "studentNow"=> 0,
            "studentHistory"=> 0,
            "hit"       => 0,
            "likes"     => 0,
            "uniqueId"  => md5(time().uniqid())
        );
        $data = array();
        foreach ($defaults as $k => $v) {
            if (isset($params[$k]) && $params[$k] !== "") {
                $data[$k] = $params[$k];
            }
        }
        $qb = $this->getQueryBuilder();
        if (isset($params["id"])) {
            //编辑
            $qb->update("Course");
            $qb->where("id = :id")->setParameter("id",$params["id"]);
            foreach ($data as $key => $val) {
                $qb->set("$key",":$key")->setParameter(":$key",$val);
            }
        } else {
           return false;
        }
        $qb->execute();
        if ( $qb->getState() === 1) {
            return $data["uniqueId"];
        } else {
            return $qb->getState();
        }
    }



    /**
     * @param array $params $param[textKey]=textKey , $param[conditions][table][field][eq|gt|lt...]=value , $param[orderBy][table][field]=DESC|ASC
     * @param int $offset
     * @param int $perPage
     * @return array
     */
    public function commLists($params ,$offset = 0 , $perPage = 10)
    {
        $qb = $this->getQueryFromParam($params);
//        var_dump($qb->getSQL());die;
        $lists = $this->getAllResult($qb,$offset,$perPage);
        $total = $this->countAllResult($qb);

        return array(
            "total" => $total ? $total : 0,
            "data"  => $lists
        );
    }

    public function addHit($courseId)
    {
        $course = $this->getOneById($courseId);
        $param = array(
            "id"            => $courseId,
            "hit"           => $course["hit"] + 1,
            "uniqueId"      => $course["uniqueId"]
        );
        $this->commUpdate($param);
    }

    public function getStatistic($idOrUniqueId)
    {
        if (!is_numeric($idOrUniqueId)) {
            $course = $this->getOneByUniqueId($idOrUniqueId);
            $idOrUniqueId = $course["id"];
        }

        //喜欢
        $courseLikesModel = new CourseLikesModel($this->getDoctrine());
        $likes = $courseLikesModel->countCourseLikes($idOrUniqueId);

        //收藏
        $courseCollectModel = new CourseCollectModel($this->getDoctrine());
        $collect = $courseCollectModel->countCourseCollect($idOrUniqueId);

        //课时数量
        $courseLessonContentModel = new CourseLessonContentModel($this->getDoctrine());
        $lesson = $courseLessonContentModel->countCourseLesson($idOrUniqueId);

        return array(
            "likes"     => $likes,
            "collect"   => $collect,
            "lesson"    => $lesson,
        );
    }

    public function getList($params,$offset,$perPage)
    {
        //$params[ "search"] = "STRING"
        //$params[ "where" ][table][field][eq|gt|lt...] = value
        //$params["orderBy"][table][field] = DESC|ASC
        //$params["groupBy"][table] = field

        $textKey = isset($params[ "search"]) ? $params[ "search"] : false;
        $where   = isset($params[ "where" ]) ? $params[ "where" ] : array();
        $orderBy = isset($params["orderBy"]) ? $params["orderBy"] : array();
        $groupBy = isset($params["groupBy"]) ? $params["groupBy"] : array();

        //todo 展示时限制只显示一个课程
        $where["Course"]["id"]["eq"] = 16;

        $qb = $this->getQueryBuilder();

        //重新梳理列表
        $qb->from("Course");
        $select = array("Course"=>array("id", "category","title", "picCover", "updateTime", "uniqueId","hit"));
        $qb->select($this->makeSelectStringFromArray($select));

        //join Course
        $qb->leftJoin("Course","CourseCategory","CourseCategory","CourseCategory.id = Course.category");
        $select = array("CourseCategory"=>array("name"));
        $qb->addSelect($this->makeSelectStringFromArray($select));

        //join User
        $qb->leftJoin("Course","User","User","User.id = Course.userId");
        $select = array("User"=>array("account","nickName","headPic"));
        $qb->addSelect($this->makeSelectStringFromArray($select));

        //join Teacher
        $qb->leftJoin("Course","Teacher","Teacher","Teacher.userId = User.id");
        $select = array("Teacher"=>array("id","name","intro"));
        $qb->addSelect($this->makeSelectStringFromArray($select));

        //join TeacherCategory
        $qb->leftJoin("Course","TeacherCategory","TeacherCategory","Teacher.category = TeacherCategory.id");
        $select = array("TeacherCategory"=>array("name"));
        $qb->addSelect($this->makeSelectStringFromArray($select));

        //join School
        $qb->leftJoin("Course","School","School","School.id = Teacher.school");
        $select = array("School"=>array("id","name","intro","logo"));
        $qb->addSelect($this->makeSelectStringFromArray($select));

        //join CourseLikes
        $qb->leftJoin("Course","CourseLikes","CourseLikes","Course.id = CourseLikes.whom");
        $select = array("CourseLikes"=>array("count(who)"));
        $qb->addSelect($this->makeSelectStringFromArray($select));

        //join CourseCollect
        $qb->leftJoin("Course","CourseCollect","CourseCollect","Course.id = CourseCollect.whom");
        $select = array("CourseCollect"=>array("count(who)"));
        $qb->addSelect($this->makeSelectStringFromArray($select));

        //count后必须group
        $qb->groupBy("Course.id");

        //$params["textKey"] = "STRING"
        if ($textKey !== false) {
            //关键词搜索用or链接内部
            $search = $qb->expr()->orX();
            //逐个添加查找
            $search->add($qb->expr()->like("Course.title",":searchText"));
            //与外部使用and链接
            $qb->andWhere($search)->setParameter("searchText"   , $textKey);
        }

        //$params["where"][table][field][eq|gt|lt...]=value
        if (!empty($where)) {
            $cond = $qb->expr()->andX();
            foreach ($where as $table => $fieldDetails) {
                foreach ($fieldDetails as $fieldName => $dbVal) {
                    $ConditionType =array_keys($dbVal)[0];
                    $ConditionValue = array_values($dbVal)[0];
                    switch ($ConditionType) {
                        case "in":
                            $cond->add($qb->expr()->in($table.".".$fieldName,$ConditionValue));
                            break;
                        default:
                            $cond->add($qb->expr()->$ConditionType($table.".".$fieldName,":$table$fieldName"));
                            $params["$table$fieldName"] = $ConditionValue;
                    }
                }
            }
            $qb->andWhere($cond);
            foreach ($params as $k=>$v) {
                $qb->setParameter($k,$v);
            }
        }
        //$params["orderBy"][table][field]=DESC|ASC
        if (!empty($orderBy)) {
            foreach ($orderBy as $entityName => $orderBys) {
                foreach ($orderBys as $orderKey => $order) {
                    $qb->orderBy("$entityName"."."."$orderKey",$order);
                }
            }
        }
        //$params["groupBy"][table] = field
        if (!empty($groupBy)) {
            foreach ($groupBy as $entityName => $fields) {
                foreach ($fields as $field) {
                    $qb->addGroupBy($entityName.".".$field);
                }
            }
        }
        $lists = $this->getAllResult($qb,$offset,$perPage);
        $total = $this->countAllResult($qb);

        return array(
            "total" => $total ? $total : 0,
            "data"  => $lists
        );
    }

    public function makeSelectStringFromArray($params)
    {
        $selectString = "";
        foreach ($params as $table => $fields) {
            foreach ($fields as $field) {
                if (strpos($field,"(")>0) {
                    $fieldName = str_replace("(","(".$table.".",$field);
                    preg_match("/\((.+)\)/",$field,$matches);
                    $aliasName = $table."_".$matches[1];
                } else {
                    $fieldName = $table.".".$field;
                    $aliasName = $table."_".$field;
                }
                $selectString .= $selectString == "" ? "":",";
                $selectString .= " $fieldName as $aliasName";
            }
        }
        return $selectString;
    }


    public function getListForWebIndex($params,$offset,$perPage)
    {
        //$params[ "search"] = STRING
        //$params[ "where" ][table][field][eq|gt|lt...] = value
        //$params[ "where" ][table][field][in] = ARRAY
        //$params["orderBy"][table][field] = DESC|ASC
        //$params["groupBy"][table] = field

        return $this->getList($params,$offset,$perPage);
    }

}